<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <div class="min-fire-station-info-wrap">
                <el-form label-width="150px" :model="minFireStationForm" :rules="minFireStationFormRules" ref="minFireStationForm" @submit.native.prevent>
                    <el-form-item label="联网单位：" prop='organizationId'>
                        <el-select filterable v-model="minFireStationForm.organizationId">
                            <el-option
                                v-for="item in orgList"
                                :key="item.organizationId"
                                :label="item.shortName"
                                :value="item.organizationId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="名称：" prop="name">
                        <el-input v-model="minFireStationForm.name" auto-complete="off" placeholder="请输入名称"></el-input>
                    </el-form-item>
                    <el-form-item label="位置：" prop="location">
                        <el-input v-model="minFireStationForm.location" auto-complete="off" placeholder="请输入位置"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话：" prop="tel">
                        <el-input v-model="minFireStationForm.tel" auto-complete="off" placeholder="请输入联系电话"></el-input>
                    </el-form-item>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="经度：" prop="lon">
                                <el-input v-model="minFireStationForm.lon" auto-complete="off" placeholder="请输入经度"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="纬度：" prop="lat">
                                <el-input v-model="minFireStationForm.lat" auto-complete="lat" placeholder="请输入纬度"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="选取经纬度：">
                        <div id="MiniFireStationInfoBaiduMap" style="width:100%;height:300px"></div>
                        <input id="unitName_mapInput" class="form-control" v-model="valtemp" placeholder="请输入地点"/>
                    </el-form-item>
                    <el-form-item label="责任人姓名：" prop="chargePerson">
                        <el-input v-model="minFireStationForm.chargePerson" auto-complete="off" placeholder="请输入责任人姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="责任人电话：" prop="chargePhone">
                        <el-input v-model="minFireStationForm.chargePhone" auto-complete="off" placeholder="请输入责任人电话"></el-input>
                    </el-form-item>
                    <el-form-item label="战斗人数：" prop="scale">
                        <el-input type="number" v-model="minFireStationForm.scale" auto-complete="off" placeholder="请输入战斗人数" :min="0"></el-input>
                    </el-form-item>
                    <el-form-item label="图片：" prop='pictures'>
                        <el-upload
                            :action="QINIUUPLOADURL"
                            :multiple="false"
                            ref="upload"
                            list-type="picture-card"
                            :data="qiniuData"
                            :on-success="handleAvatarSuccess"
                            :on-remove="handleRemovePic"
                            :on-error="handleError"
                            :before-upload="beforeAvatarUpload"
                            :on-preview="$imgPreview"
                            :file-list="qiniuData.fileList"
                            :limit="1"
                            :on-exceed="handleExceed"
                            accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label-width="0" class="verifyidentity-button">
                        <el-button @click.stop="closeFun" round>取消</el-button>
                        <el-button type="primary" @click="saveInfo('minFireStationForm')" round>保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-col>
    </el-row>
</template>
<script>
import BMap from 'BMap';
import util from '@/utils/util';
import { qnToken} from '@/api/api';
import { getOrgList } from '@/api/org';
import { updateMiniFireHouses } from '@/api/sysConfig';
import { setTimeout } from 'timers';
import { watch } from 'fs';

var map;
 export default {
    name:"ImportAsset",
    props: {
        oldInfo: {},
        closeFun: {
            type: Function,
            required: true,
        }
    }, 
    data() {
        return {
            valtemp:'',
            qiniuData:{//上传图片携带的参数
                token : "",
                key : "",
                fileList:[],
            },
            minFireStationForm: {
                organizationId: '',
                name:'',
                location:'',
                lat:'',
                lon:'',
                chargePerson:'',
                chargePhone:'',
                scale:'',
                tel:'',
                id:'',
                url:''
            },
            orgList: [],
            minFireStationFormRules:{
                organizationId: [{ 
                    required: true, message: '请选择业主单位', trigger: 'change' 
                }],
                name: [{ 
                    required: true, message: '请输入名称', trigger: 'blur' 
                }],
                chargePerson:[
                     { required: true, message: '请输入责任人姓名', trigger: 'blur' },
                ],
                chargePhone:[
                     { required: true, message: '请输入责任人电话', trigger: 'blur' },
                ],
                scale:[
                    { required: true, message: '请输入正确的人数', trigger: 'change' },
                    {pattern:/^[+]{0,1}(\d+)$/ , message:'请输入正确的数值'}
                ]
            }
        }
    },
    created() {
        var that = this;

        that.getToken();

        // 获取业主单位信息
        getOrgList({
            queryType: 0
        }).then(res => {
            if(res.status = 200) {
                that.minFireStationForm.organizationId = res.data[0].organizationId;
                that.orgList = res.data;
            }
        });

        that.$nextTick(() => {
            // 是否有历史值
            if(that.oldInfo.id) {
                that.minFireStationForm.organizationId = that.oldInfo.organizationId;
                that.minFireStationForm.name = that.oldInfo.name;
                that.minFireStationForm.location = that.oldInfo.location;
                that.minFireStationForm.lat = that.oldInfo.lat;
                that.minFireStationForm.lon = that.oldInfo.lon;
                that.minFireStationForm.scale = that.oldInfo.scale;
                that.minFireStationForm.chargePerson = that.oldInfo.chargePerson;
                that.minFireStationForm.chargePhone = that.oldInfo.chargePhone;
                that.minFireStationForm.tel = that.oldInfo.tel;
                that.minFireStationForm.id = that.oldInfo.id;
                // 设置上传图片初始值
                that.oldInfo.url ? $.each(that.oldInfo.url.split(','), (index,url) => {
                    that.qiniuData.fileList.push({
                        name: that.oldInfo.name + index,
                        url:url
                    })
                }) : ''
            }
            // 初始化地图
            that.initMap();
        });
    },
    methods: {
        // 地图初始化
        initMap() {
            let that = this;
            var geoc = new BMap.Geocoder();
            //选取经纬度
            map = new BMap.Map("MiniFireStationInfoBaiduMap");
            map.enableScrollWheelZoom(); // 允许缩放
            map.clearOverlays(); // 先清除地图上的点
            map.enableKeyboard(); // 启用键盘上下左右键移动地图 
            map.setDefaultCursor("crosshair"); // 设置鼠标样式

            //经纬度画线
            if(that.oldInfo.lon && that.oldInfo.lat){
                var new_point1 = new BMap.Point(that.oldInfo.lon, that.oldInfo.lat);
                var marker1 = new BMap.Marker(new_point1);  // 创建标注
                map.addOverlay(marker1);              // 将标注添加到地图中
                map.centerAndZoom(new_point1,16);
                //map.panTo(new_point1); 
            }else{
                var position = new BMap.Point(116.331398,39.897445);
                map.centerAndZoom(position, 16); 
            }

            map.addEventListener("click", function(e){   
                // 通过点击百度地图，可以获取到对应的point, 由point的lng、lat属性就可以获取对应的经度纬度     
                var pt = e.point;
                geoc.getLocation(pt, function(rs){
                    // addressComponents对象可以获取到详细的地址信息
                    var addComp = rs.addressComponents;
                    var addr = addComp.province +","+ addComp.city +","+addComp.district +","+ addComp.street +","+ addComp.streetNumber
                    // 打点
                    map.clearOverlays() // 先清除地图上的点
                    var marker = new BMap.Marker(pt);  // 创建标注
                    map.addOverlay(marker);              // 将标注添加到地图中
                    // 经纬度设置值
                    that.minFireStationForm.location = addr
                    that.minFireStationForm.lon = pt.lng;
                    that.minFireStationForm.lat = pt.lat;
                })     
            })
            setTimeout(() => {
                that.mapSearch();
            }, 1000)
        },
        // 搜索经纬度
        mapSearch() {
            var acSearch = new BMap.Autocomplete({'input' : 'unitName_mapInput', 'location' : map});
            acSearch.setInputValue(this.valtemp);
            acSearch.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
                var _value = e.item.value; 
                var myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
                var local = new BMap.LocalSearch( map, { //智能搜索
                    onSearchComplete: function(results) {
                        var position=results.getPoi(0);//得到标注点坐标
                        var lng = position.point.lng;
                        var lat = position.point.lat;
                        var gpsPoint = new BMap.Point(lng,lat);
                        map.centerAndZoom(gpsPoint,16);
                    }
                 });
                local.search(myValue);
            });
        },
        getToken(){  //上传之前获取 token
            qnToken({}).then((result) => {
                this.qiniuData.token= result.data;
            });
        },
        beforeAvatarUpload(file) {//重命名和校验
            var fielLocal = file.name.split(".");
            var fielType = "." + fielLocal[fielLocal.length-1];
            var fielLocalName = fielLocal[0];
            this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType;
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt20M = file.size / 1024 / 1024 < 20;
            if (!isJPG && !isPNG) {
                this.$message.error("图片只能是 JPG/PNG 格式!");
                return false;
            }
            if (!isLt20M) {
                this.$message.error("图片大小不能超过 20MB!");
                return false;
            }
        },
        handleAvatarSuccess: function(res, file, fileList) {//上传成功
            this.qiniuData.fileList = fileList;
        },
        handleRemovePic: function(file, fileList) {//删除成功
            this.qiniuData.fileList = fileList;
        },
        handleError: function(res) {
            this.$message({
                message: "上传失败",
                duration: 2000,
                type: "warning"
            });
        },
        handleExceed(files, fileList) {//文件超出个数限制时的钩子
            this.$message.warning(`只能上传一张图片！`);
        },
        /* 保存数据 */
        saveInfo(formName) {
            let that = this;
            // 阻止事件冒泡
            event.stopPropagation();

            that.$refs[formName].validate((valid) => {
                if (valid) {
                    let parames = that.minFireStationForm;
                    parames.url = util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString();
                     
                    // 提交
                    updateMiniFireHouses(parames).then(res => {
                        if(res.status === 200) {
                            that.$message({
                                message: '保存成功！',
                                type: 'success'
                            });
                            that.closeFun(true);
                        } else {
                            that.$message({
                                message: res.info,
                                type: 'warning'
                            })
                        }
                    });
                } else {
                    return false;
                }
            });
        },
    },
    watch:{
        //校验战斗人数不为00000
        scaleVal(val,oldVal){
            if(val!==oldVal){
                this.minFireStationForm.scale = Number(val)
            }
        }
    },
    computed:{
        scaleVal(){
            return this.minFireStationForm.scale
        }
    }
 }
</script>
<style lang="scss">
.min-fire-station-info-wrap {
    #unitName_mapInput {
        position: absolute;
        left: 5%;
        top: 8px;
        padding: 0 10px;
        width: 50%;
        background-color: rgba(255, 255, 255, 0.8);
        height: 38px;
        color: #333;
        border: 0;
        border-top: 1px solid #eee;
        border-left: 1px solid #eee;
        border-right: 1px solid #eee;
        border-radius: 2px 0 0 2px;
        box-shadow: 1px 1.5px 1px rgba(0,0,0,.25);
    }
}
.tangram-suggestion-main {
    z-index: 9999999999;
}
</style>
